/**
 * 通用的mongodb连接池连接。
 *
 * 使用：
 * var mongoConnect = require('../utils/mongodb_connect');
 *Post.getTen = function (name, page, callback) {
 *   mongoConnect((err, client, release)=> {
 *       if (err) {
 *           release();
 *           return callback(err);
 *       }
 *
 *       client.collection('posts').count(query, (err, total)=> {
 *              //..........
 *       })
 *   });
 *
 *};
 *
 */

var poolModule = require('generic-pool');
var MongoClient = require('mongodb').MongoClient;

var options = require('../config').mongodb || {};
var host = options.host;
var port = options.port || 27017;
var user = options.user;
var password = options.password;
var db = options.db;

var url = options.url;
if (!url) {
    if (user && password) {
        url = "mongodb://" + user + ":" + password + "@" + host + ":" + port;
    } else {
        url = "mongodb://" + host + ":" + port;
    }
    url += "/" + db;
}
//TODO replicaSet（副本）
//TODO proxy（代理）


//简单的连接池
var mongoPool = poolModule.Pool({
    name: 'mongodb',
    create: function (callback) {
        MongoClient.connect(url, {
            poolSize: 1
        }, callback);
    },
    destroy: function (client) {
        client.close();
    },
    max: options.max || 100,
    min: options.min || 1,
    idleTimeoutMillis: options.timeout || 30000,
    log: options.log || false
});

module.exports = function (callback, priority) {

    mongoPool.acquire(function (err, client) {

        var release = function () {
            mongoPool.release(client);
        }
        if (err) {
            release();  //释放
            callback(err);  //回调。按照规则函数的第一个参数是error
        }
        callback(err, client, release);

    }, priority);

}








